<template>
  <v-item-group mandatory v-model="selectedIndex" selected-class="selected">
    <v-container class="rows">
      <v-row>
        <v-col
          v-for="(item, index) in formItems"
          :key="index"
          :cols="item.span / 2"
        >
          <v-item :value="index" v-slot="{ selectedClass, toggle }">
            <v-card
              :text="format(item) || '/'"
              class="cell border no-shadow"
              :class="getCellClass(index, selectedClass)"
              @click="toggle?.()"
            >
            </v-card>
          </v-item>
        </v-col>
      </v-row>
    </v-container>
  </v-item-group>
  <v-container>
    <v-row justify="end">
      <v-col :lg="2" :md="3" :sm="3">
        <v-btn block @click="reset">重置</v-btn>
      </v-col>
      <v-col :lg="3" :md="4" :sm="4">
        <v-btn color="blue" block variant="elevated" @click="addFormItems"
          >新增表单项</v-btn
        >
      </v-col>
    </v-row>
  </v-container>
</template>
<script setup lang="ts">
import hotkeys from "hotkeys-js";
import { FormItem, FormItemDisplay } from "@/types";
import { useConfigs, useFormItems } from "@/features";
const { opAreaConfig } = useConfigs();

const {
  formItems,
  resetFormItems,
  selectedIndex,
  setSelectedIndex,
  increaseFormItems,
  isSelected,
  removeFormItem,
  selectedItem,
} = useFormItems();

hotkeys("backspace,delete", () => {
  const index = selectedIndex.value;
  if (index === -1 || formItems.length <= 1) return;

  const del = () => removeFormItem(index);
  const { label, field, regExps, validators } = selectedItem.value!;
  if (label || field || regExps.length || validators.length) {
    if (window.confirm("确定删除当前选中表单项？")) {
      del();
    }
  } else {
    del();
  }
});

function reset() {
  if (window.confirm("确定重置？")) {
    resetFormItems();
    setSelectedIndex(0);
  }
}

function getCellClass(index: number, extra: any) {
  return [isSelected(index) ? "selected" : "", extra];
}

function addFormItems() {
  increaseFormItems(opAreaConfig.defaultAdditionsCount);
}

function format(item: FormItem) {
  const { label, field, required } = item;
  let head = "";
  switch (opAreaConfig.cellDisplay) {
    case FormItemDisplay.ALL:
      head = field ? `${label}（${field}）` : label;
      break;
    case FormItemDisplay.FIELD:
      head = field;
      break;
    case FormItemDisplay.LABEL:
      head = label;
      break;
  }
  return head ? (required ? `${head}（必填）` : head) : "";
}
</script>

<style lang="scss" scoped>
.rows {
  height: 616px;
  overflow: auto;

  :deep(.v-card-text) {
    text-align: center;
  }
}

.cell {
  white-space: nowrap;

  &.selected {
    color: #fff;
    background-color: #2196f3;
  }
}
</style>
